{layout name="public/layout" /}
{include file='yxnavbar'}
{include file='sms/sms_header'}


<form class="form-horizontal form" action="" id="form1" >
    <div class="panel panel-default" role="tabpanel" style="">
        <div class="panel-heading" style="background-color: #478ec8;color: #ffffff;">批量发送短信录入</div>
        <div class="panel-body" style="">
            <div class="form-group">
                <label class="col-sm-1 col-xs-12 control-label"><span style="color: red;">*</span>选择短信模版</label>
                <div class="col-sm-10 col-xs-12">
                    <select class="form-control" id="select_template" name="template_id">
                        <option value="0" {if empty($template_id) }selected="selected"{/if}>----------请选择短信模版----------</option>
                        {loop $list  $val}
                        <option value="{$val['id']}" {if $template_id == $val['id'] }selected="selected"{/if}>{$val['remark']}</option>
                        {/loop}
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 col-xs-12 control-label">短信示例</label>
                <div class="col-sm-10 col-xs-12">
                    <input class="form-control" value="{$format_item_out_template_content}" readonly>
                    <span class="help-block">一行一条发送数据用逗号(,)分号(;)分隔;重复数据系统会自动删除；</span>
                    <span class="help-block">一个手机号输入演示：{$once_notice}</span>
                    <span class="help-block">多个个手机号输入演示：</br>{php echo $more_notice;}</span>
                </div>
            </div>
            {if $item['type']=='quick'}
            <div class="form-group">
                <label class="col-sm-1 col-xs-12 control-label">录入方式</label>
                <div class="col-sm-10 col-xs-12">
                    <label class="radio-inline">
                        <input name="yx_sms_input_type" value="0" {if !$has_system_input_flag} checked="checked"{/if} type="radio"> 手动录入
                    </label>
                    <label class="radio-inline">
                        <input name="yx_sms_input_type" value="1" {if $has_system_input_flag} checked="checked"{/if} type="radio"> 系统选择
                    </label>
                </div>
            </div>
            {/if}

            <div class="form-group" id="yx_sms_system_from" style="display: none;">
                <label class="col-sm-1 col-xs-12 control-label"><span style="color: red;">*</span>选择客户分类</label>
                <div class="col-sm-10 col-xs-12">
                    <select class="form-control" id="yx_sms_mobile_type" name="yx_sms_mobile_type">
                        <option value="0" data-type="default">----------请选择客户分类----------</option>
                        {loop $sms_system_mobile_type  $val}
                        <option value="{$val['val']}" data-type="{$val['type']}">{$val['title']}</option>
                        {/loop}
                    </select>
                </div>
            </div>

            <div class="form-group" id="yx_sms_system_from_time" style="display: none;">
                <label class="col-sm-1 col-xs-12 control-label">下单时间</label>
                <div class="col-sm-10 col-xs-12">
                    {php echo view_form_field_daterange('adtime', array('start'=>date('Y-m-d H:i:s',$search_start),'end'=>date('Y-m-d H:i:s',$search_end)), true);}
                    <span class="help-block">手机号客户的下单时间</span>
                </div>
            </div>

            <div class="form-group" style="display: none;" id="match_mobile_desc">
                <label class="col-sm-1 col-xs-12 control-label">匹配说明</label>
                <div class="col-sm-10 col-xs-12">
                    <input class="form-control" id="match_mobile_desc_input" value="" readonly>
                </div>
            </div>

            <div class="form-group" id="order_list" >
                <label class="col-sm-1 col-xs-12 control-label">{if !$item['diy_template_params']}手机号列表{else}数据列表{/if}</label>
                <div class="col-sm-10 col-xs-12">
                    <textarea rows="20" cols="50" class="form-control" id="order_list_mobile"  name="order_list" {if !empty($order_list_txt)} readonly{/if}>{$order_list_txt}</textarea>
                </div>
            </div>
        </div>
    </div>
    <div class="form-group" id="sub_upload" >
        <div class="col-sm-12">
            {if $item['type']=='quick'}
            <input name="submit" onclick="checkMobile()"  id="check_mobile" type="button" value="手机号检测" class="btn btn-primary col-lg-2">
            <input name="submit" onclick="rechangeCheckMobile()" style="display: none;" id="btnConfirm4" type="button" value="重新输入手机号"
                   class="btn btn-danger col-lg-2">
            {/if}
            <input name="submit" onclick="addOrEditItem()"  id="btnConfirm" type="button" value="确认提交" class="btn btn-primary col-lg-2" {if $item['type']=='quick'}style="display: none;"{/if}>
            <input name="submit" onclick="checkOrderSmsMobile()" style="display: none;" id="btnConfirm2" type="button" value="检索手机号" class="btn btn-primary col-lg-2">
            <input name="submit" onclick="rechangeCheck()" style="display: none;" id="btnConfirm3" type="button" value="重新匹配"
                   class="btn btn-danger col-lg-2">
        </div>
    </div>
</form>
<script>
    var selected_temple_id = "<?php echo $template_id;?>";
    var send_num=1;
    var timer;
    var success_total = 0;
    var fail_total = 0;
    var yx_sms_input_type = 0;

    if (selected_temple_id==0){
        layer.alert('请选择短信模版后再进行后续操作');
    }
    //监听模版改变事件
    $("#select_template").change(function () {
        var curt_val = $("#select_template").val();
        if (curt_val==0){
            layer.alert('请选择短信模版');
        }else{
            var redirect_url = "{php echo createWebUrl('sms',array('op' => 'betch_ali','themeid'=>$themeid));}"+'&template_id='+curt_val;
            window.location.href = redirect_url;
        }
    });
    function checkMobile()
    {
        var open_yx_sms = "{php echo $open_yx_sms;}";
        if (open_yx_sms==0){
            layer.msg(' 【 短信通知未开通 】 开通请到 "群发短信" => "短信配置" 中开启，如有疑问请联系客服！');
            return;
        }
        var mobile_txt = $("#order_list_mobile").val();
        if (mobile_txt==''){
            layer.msg('手机号列表为空');
            return;
        }
        $("#check_mobile").attr("disabled",true);
        layer.msg('手机号检测中...');
        let postUrl = "{php echo createWebUrl('sms',array('op'=>'check_mobile','themeid'=>$themeid));}";
        let formData = $("#form1").serialize();
        $.ajax({
            url:postUrl,
            dataType:'json',
            method:'post',
            data:formData,
            success:function (e) {
                let status = e.status;
                let data = e.result.data;
                let msg = e.result.msg;
                console.log(data)
                let sure = data.sure;
                let format_mobile_txt = data.mobile_txt;
                if (sure>0){
                    $("#order_list_mobile").val(format_mobile_txt);
                    $("#order_list_mobile").attr("readonly","readonly");
                    $("#check_mobile").hide();
                    $("#btnConfirm").show();
                    if (yx_sms_input_type==0){
                        $("#btnConfirm4").show();
                    }

                }
                layer.msg(msg);
            },
            fail:function (err) {
                console.log(err)
            }
        })
    }
    function rechangeCheckMobile() {
        $("#order_list_mobile").val('');
        $("#order_list_mobile").removeAttr("readonly");
        $("#check_mobile").show();
        $("#btnConfirm").hide();
        $("#btnConfirm4").hide();
    }
    function addOrEditItem() {
        var open_yx_sms = "{php echo $open_yx_sms;}";
        if (open_yx_sms==0){
            layer.msg(' 【 短信通知未开通 】 开通请到 "群发短信" => "短信配置" 中开启，如有疑问请联系客服！');
            return;
        }
        let postUrl = "{php echo createWebUrl('sms',array('op'=>'betch_ali','themeid'=>$themeid));}";
        let success_redirect = "{php echo createWebUrl('sms',array('op'=>'display','themeid'=>$themeid,'type'=>$item_type_key));}";
        let formData = $("#form1").serialize();
        $.ajax({
            url:postUrl,
            dataType:'json',
            method:'post',
            data:formData,
            success:function (e) {
                let status = e.status;
                let result = e.result;
                let type = result.type;
                let template_type = result.template_type;
                let template_id = result.template_id;
                console.log(status,result);
                if (status!=1){
                    layer.msg(result.msg)
                    $("#order_list_mobile").val(result.list);
                }else{
                    if (type=='auto_send'){
                        layer.msg(result.msg);
                        setTimeout(function () {
                            window.location.href = success_redirect;
                        },1800);
                    }else{
                        //弹出队列执行
                        showWaitSend(template_id,template_type);
                    }
                }
            },
            fail:function (err) {
                console.log(err)
            }
        })
    }
    //存在大批量待执行队列弹出
    function showWaitSend(sms_template_id,template_type) {
        var checkSmsTemplateTotalUrl = "{php echo createWebUrl('sms',array('op'=>'template_queue_wait_total','themeid'=>$themeid));}";
        $.ajax({
            url:checkSmsTemplateTotalUrl,
            dataType:'json',
            method:'post',
            data:{template_id:sms_template_id},
            success:function (e) {
                let status = e.status;
                let result = e.result;
                if (status!=1){
                    layer.msg(result.msg)
                }else{
                    var total = result.count;
                    var total_txt = result.total_txt;
                    var item_type_key = result.item_type_key;
                    send_num = result.send_num;
                    var format_html = '<div id="send_sms_process" style="width: 840px;padding: 60px;">\n' +
                        '    <div class="layui-progress layui-progress-big" lay-showPercent="true" >\n' +
                        '        <div class="layui-progress-bar layui-bg-blue" id="show_sms_send_process_rate" style="width: 0%;">\n' +
                        '            <span class="layui-progress-text" id="show_sms_send_process_num">' + total_txt + '</span>\n' +
                        '        </div>\n' +
                        '    </div>\n' +
                        '        <div  id="queue_process_notice" style="text-align: center;display: none;">累计发送成功：100条，失败：1条；</div>\n' +
                        '    <div class="layui-btn-container" style="margin-top: 40px;float: right;">\n' +
                        '        <button type="button" class="layui-btn layui-btn-primary" id="cancel_send" data-templateid="'+ sms_template_id +'" onclick="hideSendSms(this)">取消发送</button>\n' +
                        '        <button type="button" class="layui-btn" id="sure_send" date-templatetype="'+ template_type +'" data-templateid="'+ sms_template_id +'" data-total="'+ total +'" onclick="user_sure_send_quick_sms(this)">确认发送</button>\n' +
                        '        <button type="button" style="display: none;" class="layui-btn" id="jump_send_log" data-typekey="'+ item_type_key +'"  onclick="jump_send_log(this)">发送完毕，查看发送记录</button>\n' +
                        '    </div>\n' +
                        '</div>';
                    layer.open({
                        type:1,
                        title:'模版短信发送',
                        area: ['840px', '240px'], // 宽高
                        content: format_html
                    });
                }
            },
            fail:function (err) {
                console.log(err)
            }
        })
    }
    //轮训请求执行队列
    function user_sure_send_quick_sms(e) {
        $('#cancel_send').hide();
        $('#sure_send').html('发送执行中...');
        $('#sure_send').attr('disabled',"true");
        var all_process = 0;
        var template_id = e.getAttribute('data-templateid');
        var queue_total = e.getAttribute('data-total');
        var template_type = e.getAttribute('data-templatetype');

        var wait_send_num = Math.ceil(queue_total/100);
        var once_add_process = Math.ceil(100/wait_send_num);
        var action_num = 0;
        timer = setInterval(function () {
            var postUrl = "{php echo createWebUrl('sms',array('op'=>'queue_sms_template_send','themeid'=>$themeid));}";
            let success_redirect = "{php echo createWebUrl('sms',array('op'=>'display','themeid'=>$themeid,'type'=>$item_type_key));}";
            $.ajax({
                url:postUrl,
                dataType:'json',
                method:'post',
                data:{template_id:template_id},
                success:function (e) {
                    let status = e.status;
                    let result = e.result;
                    success_total += result.success_total;
                    fail_total += result.fail_total;
                    if (status!=1){
                        clearInterval(timer);
                        $('#sure_send').html('发送异常');
                        layer.msg(result.msg)
                        setTimeout(function () {
                            window.location.reload();
                        },1500);
                    }else{
                        action_num+=1;
                        all_process += once_add_process;
                        if (all_process>100){
                            all_process = 100;
                        }
                        var format_all_process = all_process+'%';
                        $('#show_sms_send_process_rate').width(format_all_process);
                        if (template_type!='quick'){
                            if (queue_total<100){
                                var process_txt = queue_total+" / "+queue_total;
                            }else{
                                var curt_process_num = action_num*100;
                                if (curt_process_num>queue_total){
                                    curt_process_num = queue_total;
                                }
                                var process_txt = curt_process_num+" / "+queue_total;
                            }
                        }else{
                            if (queue_total<100){
                                var process_txt = queue_total+" / "+queue_total;
                            }else{
                                var curt_process_num = action_num*100;
                                if (curt_process_num>queue_total){
                                    curt_process_num = queue_total;
                                }
                                var process_txt = curt_process_num+" / "+queue_total;
                            }
                        }

                        $("#show_sms_send_process_num").html(process_txt);
                        if (send_num>0){
                            send_num-=1;
                        }
                        if (send_num<1){
                            clearInterval(timer);
                            // $('#sure_send').html('发送完毕');
                            var show_sms_queue_process_notice = '累计发送成功:'+success_total+'条；发送失败:'+fail_total+'条';
                            $("#queue_process_notice").html(show_sms_queue_process_notice);
                            $("#queue_process_notice").show();
                            $('#sure_send').hide();
                            $('#jump_send_log').show();
                        }
                    }
                },
                fail:function (err) {
                    console.log(err)
                    clearInterval(timer);
                    return;
                }
            })
        },'6000');
    }
    function hideSendSms(e) {

        var template_id = e.getAttribute('data-templateid');
        var postUrl = "{php echo createWebUrl('sms',array('op'=>'delete_queue_sms','themeid'=>$themeid));}";
        $.ajax({
            url:postUrl,
            dataType:'json',
            method:'post',
            data:{template_id:template_id},
            success:function (e) {
                let status = e.status;
                let result = e.result;
                layer.msg(result.msg)
                setTimeout(function () {
                    window.location.reload();
                },1000);

            },
            fail:function (err) {
                console.log(err)
                clearInterval(timer);
                return;
            }
        })
    }

    $("input:radio[name=yx_sms_input_type]").change(function () {
        var _this = $(this);
        if (_this.val()==1){
            $('#check_mobile').hide();
            $('#order_list').hide();
            $('#btnConfirm').hide();
            $('#btnConfirm2').show();
            $('#yx_sms_system_from').show();
            $('#yx_sms_system_from_time').show();
            yx_sms_input_type=1;
        }else {
            $('#check_mobile').show();
            $('#order_list').show();
            $('#btnConfirm2').hide();
            $('#btnConfirm').show();
            $('#yx_sms_system_from').hide();
            $('#yx_sms_system_from_time').hide();
            yx_sms_input_type=0;
        }
    });
    function checkOrderSmsMobile() {
        var yx_sms_mobile_type = $("#yx_sms_mobile_type").val();
        var yx_sms_mobile_type_type = $("#yx_sms_mobile_type").find('option:selected').attr("data-type");
        var start_time = $("input[name='adtime[start]']").val();
        var end_time = $("input[name='adtime[end]']").val();
        if (!yx_sms_mobile_type || yx_sms_mobile_type==0){
            layer.msg('请选择客户分类');
            return
        }
        $("#btnConfirm2").attr("disabled",true);
        layer.msg('检索手机号中...');
        var postUrl = "{php echo createWebUrl('sms',array('op'=>'betch_ali_match','themeid'=>$themeid));}";
        $.ajax({
            url:postUrl,
            dataType:'json',
            method:'post',
            data:{mobile_type:yx_sms_mobile_type,mobile_type_type:yx_sms_mobile_type_type,start_time:start_time,end_time:end_time},
            success:function (e) {
                let status = e.status;
                let result = e.result;
                console.log(status,result);
                if (status!=1){
                    layer.msg(result.msg)
                }else{
                    var total = result.data.total;
                    var mobile = result.data.mobile_txt;
                    $("#order_list_mobile").html(mobile);
                    $("#order_list").show();
                    var show_txt = '匹配到'+total+'个手机号';
                    $("#match_mobile_desc_input").val(show_txt);
                    $("#match_mobile_desc").show();
                    $("#check_mobile").show();
                    $("#btnConfirm2").hide();
                    $("#btnConfirm3").show();
                    $("#btnConfirm2").removeAttr("disabled");
                }
            },
            fail:function (err) {
                console.log(err)
            }
        })
    }
    function rechangeCheck() {
        $("#match_mobile_desc").hide();
        $("#order_list_mobile").val();
        $("#order_list").hide();
        $("#btnConfirm3").hide();
        $("#btnConfirm2").show();
        $("#btnConfirm").hide();
    }
    function jump_send_log(e) {
        var type_key = e.getAttribute('data-typekey');
        var jump_url = "{php echo createWebUrl('sms',array('op'=>'display','themeid'=>$themeid));}"+'&type='+type_key;
        window.location.href = jump_url;
    }
</script>
